package com.ayoka.parenting.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.AbsoluteLayout;
import android.widget.ProgressBar;

import com.ayoka.parenting.R;
import com.jincp.common.utils.UIUtils;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;
import java.util.Map;


/**
 * Wing_Li
 * 2016/9/9.
 */
public class ProgressWebView extends WebView {

    public ProgressBar mProgressBar;
    private ActivityView activityView;

    protected boolean isOnPause;

    public ProgressWebView(Context context) {
        super(context);
    }

    public ProgressWebView(Context context, AttributeSet arg1) {
        super(context, arg1);
    }

    public void setActivityView(ActivityView activityView) {
        this.activityView = activityView;
        initProgressBar(activityView.getActivity());
        initWebViewSettings();
        initWebViewClient();
        initWebChromeClient();
        // 1 设置js方法名
        addJavascriptInterface(this, "Android");
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebViewSettings() {
        WebSettings webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(false);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    private void initProgressBar(Context context) {
        mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        mProgressBar.setLayoutParams(new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, 8, 0, 0));

        Drawable drawable = context.getResources().getDrawable(R.drawable.progressbar_webview);
        mProgressBar.setProgressDrawable(drawable);
        addView(mProgressBar);
    }

    private void initWebChromeClient() {
        WebChromeClient webChromeClient = activityView.getWebChromeClient();
        if (webChromeClient == null){
            webChromeClient = new DefaultChromeClient();
        }
        this.setWebChromeClient(webChromeClient);
    }

    private void initWebViewClient() {
        WebViewClient webViewClient = activityView.getWebViewClient();
        if (webViewClient == null){
            webViewClient = new DefaultWebViewClient();
        }
        this.setWebViewClient(webViewClient);
    }

    public void setProgressBarVisibility(boolean isVisibility) {
        if (isVisibility) {
            mProgressBar.setVisibility(VISIBLE);
        } else {
            mProgressBar.setVisibility(GONE);
        }
    }

    private class DefaultWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            imgReset();
            if (getMeasuredHeight() > UIUtils.getScreenHeight()) {
                heightReset();
            }
        }

        /**
         * 防止加载网页时调起系统浏览器 重定向回退bug
         */
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("alipays:") || url.startsWith("alipay") || url.startsWith("weixin://wap/pay?")) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    activityView.getActivity().startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("ProgressWebView", "无支付app");
                }
                return true;
            }
            if (url.startsWith("https://wx.tenpay.com")) {
                Map extraHeaders = new HashMap();
                extraHeaders.put("Referer", "http://api-wechat.1chex.com");//例如 http://www.baidu.com
                view.loadUrl(url, extraHeaders);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
            sslErrorHandler.proceed();
        }
    };

    public void setOnPause() {
        try {
            onPause();
            isOnPause = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setOnResume() {
        try {
            if (isOnPause) {
                onResume();
                isOnPause = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setOnDestroy() {
        setVisibility(View.GONE);
        removeAllViews();
        isOnPause = false;
        try {
            destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class DefaultChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                mProgressBar.setVisibility(GONE);
            } else {
                if (mProgressBar.getVisibility() == GONE)
                    mProgressBar.setVisibility(VISIBLE);
                mProgressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    /**
     * 重新计算高度
     */
    private void heightReset() {
        // 2 调用js方法  获取高度
        loadUrl("javascript:App.reSize(document.body.getBoundingClientRect().height)");
    }

    /**
     * 重新计算图片高度
     */
    private void imgReset() {
//        loadUrl("javascript:(function(){" +
//                "var objs = document.getElementsByTagName('img'); " +
//                "for(var i=0;i<objs.length;i++)  "
//                + "{"
//                + "var img = objs[i];   "
//                + " img.style.maxWidth = '100%';img.style.height='auto';" +
//                "}"
//                + "})()");
        /**
         * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
         **/
        loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName('img'); "
                + "for(var i=0;i<objs.length;i++)  "
                + "{"
                + "var img = objs[i];   "
                + "    img.style.maxWidth = '100%'; img.style.height = 'auto';  "
                + "}"
                + "})()");

        /**
         *  html加载完成之后，添加监听图片的点击js函数
          */
        loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName(\"img\"); "
                + "for(var i=0;i<objs.length;i++)  "
                + "{"
                + "    objs[i].onclick=function()  "
                + "    {  "
                + "        android.openImage(this.src);  "
                + "    }  "
                + "}"
                + "})()");

    }

    /**
     * 去掉底部的空白内容  重新设置高度
     *
     * @param height
     */
    @JavascriptInterface
    public void reSize(final float height) {
        // 3 使用获取的高度动态设置webview高度
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                int Height = (int) (height * getResources().getDisplayMetrics().density);
                ViewGroup.LayoutParams layoutParams = getLayoutParams();
                layoutParams.height = Height;
                setLayoutParams(layoutParams);
            }
        });
    }

    public  interface  ActivityView{
        Activity getActivity();

        WebViewClient getWebViewClient();

        WebChromeClient getWebChromeClient();
    }

}